<?php
require_once 'global.php';
require_once 'tool.php';
$option = $_REQUEST['option'];
$opts = array(
    'http' => array(
        'method' => 'GET',
        'timeout' => 5
    )
);
$timeout = stream_context_create($opts);

switch ($option) {
    case "sendMsg":
        sendMsg();
        break;
    case "getHistory":
        getHistory();
        break;
    case "submit":
        submit();
        break;
    case "getLaster":
        getLaster();
        break;
    case "isNewMsg":
        isNewMsg();
        break;
    case "update":
        update();
    case "getAreaInfo":
        getAreaInfo();
        break;
    case "updateSession":
        updateSession();
        break;
    default:
        break;
}

function sendMsg()
{
    // 获取参数，并将用户的问题和问财的答案存入数据库
    global $noAccessWebChat;
    $db = conn();
    $final["data"]['id'] = 0;
    $innerver = mysql_real_escape_string($_REQUEST['innerver']);
    $appver = mysql_real_escape_string($_REQUEST['appver']);
    $hangqing = mysql_real_escape_string($_REQUEST['hangqing']);
    $returl = mysql_real_escape_string($_REQUEST['returl']);
    $model = mysql_real_escape_string($_REQUEST["model"]);
    $sdknum = mysql_real_escape_string($_REQUEST["sdknum"]);
    $for = mysql_real_escape_string($_REQUEST["for"]);
    $userid = ($_REQUEST['userid']) ? mysql_real_escape_string($_REQUEST['userid']) : 0;
    $uname = ($_REQUEST['username']) ? mysql_real_escape_string($_REQUEST['username']) : mysql_real_escape_string($_REQUEST["deviceid"]); // username赋值
    $new_session = ($_REQUEST['new_session']) ? 1 : mysql_real_escape_string($_REQUEST['new_session']); // 判断真假0为假，当传过来的new_session为0，赋值为0
    $topicId = isset($_REQUEST['topicId']) ? mysql_real_escape_string(trim($_REQUEST['topicId'])) : ''; // 这个字段是针对搜索类提问的
    $userAndSessionCode = isset($_REQUEST['userAndSessionCode']) ? mysql_real_escape_string($_REQUEST['userAndSessionCode']) : '';
    
    $content = $_POST['content'];
    $content = mysql_real_escape_string(urlencode("$content"));
    $add_info = $_REQUEST['add_info'] ? mysql_real_escape_string(urlencode($_REQUEST['add_info'])) : "";
    $add_info = $_REQUEST['add_info'] ? 'add_info=' . $add_info : "";
    $platform = mysql_real_escape_string(urldecode($_REQUEST['platform'])) ? mysql_real_escape_string(urldecode($_REQUEST['platform'])) : 'system';
    $build = mysql_real_escape_string($_REQUEST["build"]);
    $serverAddr = mysql_real_escape_string($_REQUEST["serverAddr"]);
    $deviceid = $_REQUEST["deviceid"];
    $cate = mysql_real_escape_string($_REQUEST["cate"]);
    $showPlatForm = $platform;
    $area = getArea();
    if ($platform == '' || $platform == 'ipad' || $platform == 'iphone') { // 判断平台
        $showPlatForm = "iphone";
    } elseif ($platform == "wphone") {
        $showPlatForm = "wphone";
    } else {
        $showPlatForm = "gphone";
    }
    $source = $_REQUEST["source"] ? mysql_real_escape_string($_REQUEST["source"]) : "general";
    $url = sprintf(URL, $content, $userid, $new_session, $source, $uname, $topicId);
    // file_put_contents('/data/www/html/zhangxihang/data/tmp.txt', $url);
    
    $content = mysql_real_escape_string(trim($_REQUEST['content']));
    if ($content === '' && ! $_FILE['file'] && empty($_REQUEST['file'])) { // 检查提交的内容是否为空
        $final['errorcode'] = - 1;
        $final['errormsg'] = '提交内容不能为空';
        sendMessageToAJAX($final);
        exit();
    }
    // 不为空，发送到问财，得到反馈结果
    $result = "0";
    if ($content != "") {
        $final = curl_get($url, $for);
        $result = getResult($final);
    }
    $final['acc_operator'] = 0;
    // 判断是否接入人工（ 用户问题无法识别时）
    if ($final['data']['answer_status'] == 0 && isWorkTime()) {
        $final['acc_operator'] = 1;
    }
    $answer = $final["data"]['saveanswer'];
    // 判断是否是bank,是就转化成fund
    if ($for == 'bank') {
        $for = 'fund';
    }
    // 判断是否是zhenge和wealth,是的话转换成对应的手机炒股for
    if ($for == 'zhengu' || $for == 'wealth' || $for == '') {
        if ($showPlatForm == 'wphone') {
            $for = 'ths_am_wphone_login';
        } else 
            if ($showPlatForm == 'gphone') {
                $for = 'ths_am_gphone_login';
            } else {
                $for = 'ths_am_iphone_login';
            }
    }
    
    $imagepath = '';
    // 拿到上传的图片
    $imagepath = pic_get($showPlatForm, $appver, $userid);
    // 当发送图片的时候，返回给前端如下
    if ($imagepath != "") {
        $answer = "您的图片工作人员已经收到，为了更方便地解决您的问题，请您确保用文字详细描述过您的问题：）";
        $final['errorcode'] = "0";
        $final["data"]['answer'] = "您的图片工作人员已经收到，为了更方便地解决您的问题，请您确保用文字详细描述过您的问题：）";
    }
    if ($content != ' ' && (! empty($_POST['file']) || $_FILE['file'])) {
        $content = $content . "【图片】";
    } else 
        if ($content === '' && (! empty($_POST['file']) || $_FILE['file'])) {
            $content = "【图片】";
        }
    
    // 将前台页面传过来的字段存储到数据库
    // 新的会话执行保存到数据库，不是新的会话，将问题和答案追加到上一次执行的id数据中
    $id = $_REQUEST['id'];
    if ($new_session == 0) {
        $sql_suggest = sprintf("insert into suggest set hangqingfk='%s',question='%s', `user`='%s', valid=1, ctime= now(), platform='%s', appver='%s', sdknum='%s', `for`='%s', `server`='%s', `image`='%s', `category`='%s', build='%s',answer ='%s',model = '',question_type='%s',similar_topic='%s'", $hangqing, $content, $uname, $platform, $appver, $sdknum, $for, $serverAddr, $imagepath, $cate, $build, $answer, $final["data"]['question_type'], json_encode(array_urlencode($final["data"]["similar_topic"]))); // add
        if (mysql_query($sql_suggest, $db)) {
            $id = mysql_insert_id();
        }
        $final["data"]['id'] = $id;
        $ip = getIP(); // 获取IP
        $sql_detail = 'insert into suggest_detail set ';
        $insert_data = array(
            "hangqingfk" => $hangqing,
            "build" => $build,
            "source" => $source ? $source : "system",
            "userid" => $userid,
            "uname" => $uname,
            "platform" => $platform,
            "content" => ($content),
            "ip" => $ip,
            "appver" => $appver,
            "pid" => $id,
            "model" => $model,
            "sdknum" => $sdknum,
            "`for`" => $for ? $for : 'ths_am_iphone_login',
            "`server`" => $serverAddr,
            "innerver" => $innerver,
            "image" => $imagepath,
            "category" => $cate ? $cate : 0,
            "answer" => getAnswer($answer),
            "result" => $result,
            'area' => $area
        );
        
        $insert_data['ctime'] = time();
        $i = 0;
        foreach ($insert_data as $key => $data) {
            if ($i == 0) {
                $sql_detail .= $key . '="' . $data . '"';
            } else {
                $sql_detail .= ',' . $key . '="' . $data . '"';
            }
            $i ++;
        }
        mysql_query($sql_detail, $db);
    } elseif ($new_session == 1) {
        $id = $_REQUEST['id'];
        $final["data"]['id'] = $id;
        $similar_topic = json_encode(array_urlencode($final['data']['similar_topic']));
        $sql_up = "update suggest set question=concat(question,'~!@#%^$content'),answer=concat(answer,'~!@#%^$answer'), similar_topic=concat(similar_topic,'~!@#%^$similar_topic') where id=$id ";
        if (mysql_query($sql_up, $db)) {
            $data = array();
            $data['content'] = $content;
            $data['answer'] = $answer;
            $data = json_encode($data);
            $str = $id . "_2_" . $data . "\n";
            $str_result = $id . "_1_" . $result . "\n";
            if (! file_put_contents(UPDATE_RESULT, $str, FILE_APPEND)) {
                cronLog("error_log", $str . "=>sendMsg");
            } else {
                cronLog("data_log", $str . "=>sendMsg");
            }
            if (! file_put_contents(UPDATE_RESULT, $str_result, FILE_APPEND)) {
                cronLog("error_log", $str_result . "=>sendMsg");
            } else {
                cronLog("data_log", $str_result . "=>sendMsg");
            }
        } else {
            cronLog("error_log", $sql_up . "=>sendMsg");
        }
    }
    // 判断是否接入人工（ 答案或问题一样）
    if (isSameQues($uname, $content, $answer) && isWorkTime()) {
        $final['acc_operator'] = 1;
    }
    
    /* 猎金不接入在线客服 */
    $appJudge = in_array($for, $noAccessWebChat);
    if ($appJudge) {
        $final['acc_operator'] = 0;
    }
    
    saveRecord($final, $content, $userid, $uname, $cate, $platform, $userAndSessionCode); // 在没有接入人工的情况存储一份数据到新的数据库
    sendMessageToAJAX($final);
}

function update()
{
    $db = conn();
    $id = $_REQUEST['id'];
    $content = mysql_real_escape_string(trim($_REQUEST['content']));
    $answer = $_REQUEST['answer'];
    
    // 存聊天记录表
    $sql = "select * from suggest where id=$id";
    $result = mysql_query($sql, $db);
    $res = mysql_fetch_assoc($result);
    $res['saveanswer'] = $answer;
    $res['answer'] = $answer;
    $final['data'] = $res;
    saveRecord($final, $content, '', $res['user'], $res['category']);
    
    $final["data"]['id'] = $id;
    $sql_up = "update suggest set question=concat(question,'~!@#%^$content'),answer=concat(answer,'~!@#%^$answer') where id=$id ";
    mysql_query($sql_up, $db);
    $data = array();
    $data['content'] = $content;
    $data['answer'] = $answer;
    $data = json_encode($data);
    $str = $id . "_2_" . $data . "\n";
    if (! file_put_contents(UPDATE_RESULT, $str, FILE_APPEND)) {
        cronLog("error_log", $str . "=>update");
    } else {
        cronLog("data_log", $str . "=>update");
    }
}

function getHistory()
{
    $userId = $_REQUEST['userId'];
    $num = $_REQUEST['num'];
    $limit = HISTORY_NUM;
    $skip = ($num - 1) * $limit;
    $db = connRecord();
    $sql = "select comment,sender,sender_name,from_type,question_type,additional_info,ctime from robot_chat_record where sender = '$userId' or receiver = '$userId' order by ctime desc,id desc limit $skip,$limit;";
    $result = $db->query($sql);
    while ($res = $result->fetch_assoc()) {
        $res['ctime'] = date('Y-m-d H:i:s', $res['ctime']);
        $info[] = $res;
    }
    if (empty($info)) {
        $data['code'] = 0;
        $data['msg'] = '未查询到数据';
    } else {
        $data['code'] = 1;
        $data['msg'] = '查询成功';
        $data['data'] = $info;
    }
    echo json_encode($data);
    $db->close();
    exit();
}

function submit()
{
    $db = conn();
    $result = is_numeric($_REQUEST["result"]) ? $_REQUEST["result"] : 0;
    $id = is_numeric($_REQUEST['id']) ? $_REQUEST["id"] : 0;
    if ($result == "" || $id == "") {
        $final['errorcode'] = - 1;
    } else {
        $sql = "update suggest set result=$result where id=$id ";
        mysql_query($sql);
        $str = $id . "_1_" . $result . "\n";
        if (! file_put_contents(UPDATE_RESULT, $str, FILE_APPEND)) {
            cronLog("error_log", $str . "=>submit");
        } else {
            cronLog("data_log", $str . "=>submit");
        }
        $final['errorcode'] = 0;
    }
    sendMessageToAJAX($final);
}

function getLaster()
{
    $db = conn();
    $user = mysql_real_escape_string($_REQUEST['userid']);
    $sql = "select answer from sugg_people where user='$user' and isread=0";
    $query = mysql_query($sql);
    $sql = "update sugg_people set isread=1 where user='$user'";
    mysql_query($sql);
    $data = array();
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        $data[] = $row['answer'];
    }
    $final = array();
    if (empty($data)) {
        $final['errorcode'] = 1;
    } else {
        $final['errorcode'] = 0;
    }
    $final['data'] = $data;
    sendMessageToAJAX($final);
}

function isNewMsg()
{
    $db = conn();
    $user = mysql_real_escape_string($_REQUEST['userid']);
    $sql = "select answer from sugg_people where user='$user' and isread=0";
    $query = mysql_query($sql);
    $count = 0;
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        $count ++;
    }
    $final = array();
    if ($count) {
        $final['errorcode'] = 0;
    } else {
        $final['errorcode'] = 1;
    }
    $final['count'] = $count;
    sendMessageToAJAX($final);
}

function getAnswer($str)
{
    $index = strpos($str, "<question><lr>");
    $tmpstr = substr($str, $index);
    $tmpArr = explode("<question>", $tmpstr);
    $jieguo = substr($str, 0, $index);
    $i = 0;
    if (count($tmpArr) > 6) {
        foreach ($tmpArr as $value) {
            if ($value) {
                $jieguo .= "<question>" . $value;
                $i ++;
            }
            if ($i == 5) {
                break;
            }
        }
        return $jieguo;
    }
    return $str;
}

function cronLog($path, $msg)
{
    $logdir = LOG_PATH . "/$path";
    if (! file_exists($logdir)) {
        mkdir($logdir);
    }
    $logdir .= '/' . date('Y');
    if (! file_exists($logdir)) {
        mkdir($logdir);
    }
    $logdir .= '/' . date('m') . '/';
    if (! file_exists($logdir)) {
        mkdir($logdir);
    }
    $filename = $logdir . date('d', time()) . '.log';
    $content = date("Y-m-d H:i:s", time()) . " " . $msg . " " . "\r\n";
    file_put_contents($filename, $content, FILE_APPEND);
}

/* 获取地区信息 */
function getAreaInfo()
{
    $data = array(
        'code' => 0,
        'msg' => ''
    );
    /* 初始化信息 */
    $userid = isset($_REQUEST['userid']) ? trim($_REQUEST['userid']) : 0;
    $plaform = isset($_REQUEST['platform']) ? trim($_REQUEST['platform']) : '';
    $initInfo = getB2BInfo($userid, $plaform);
    $data['initInfo'] = $initInfo;
    /* 获取地区信息 */
    $ip = getIP();
    $url = sprintf(GET_AREA_INFO, $ip);
    $res = curl($url);
    if (200 != $res['httpCode']) {
        $data['msg'] = '接口请求失败！';
        echo json_encode($data);
        exit();
    }
    $content = json_decode($res['htmlContent'], true);
    $code = $content['code'];
    $city = $content['city'];
    $conditon = array(
        0,
        2,
        4
    );
    if (! in_array($code, $conditon)) {
        $data['msg'] = '获取地理信息失败';
        echo json_encode($data);
        exit();
    }
    $flag = strpos($city, '杭州');
    if (false !== $flag) {
        $data['code'] = '1';
        $data['msg'] = '该地区为杭州地区';
    } else {
        $data['msg'] = '该地区不是杭州地区';
    }
    echo json_encode($data);
}

/* 更新会话信息 */
function updateSession($param)
{
    $logPath = B2B_LOG_PATH;
    $cate = isset($_REQUEST['cate']) ? trim($_REQUEST['cate']) : 1;
    $recordKey = trim($_REQUEST['record_key']);
    $customerId = trim($_REQUEST['customer_id']);
    $url = B2B_SESSION_UPDATA;
    $postData = array(
        'channel' => $cate,
        'record_key' => $recordKey,
        'queuing_situation' => 0,
        'customer_id' => $customerId,
        'wait_time' => 0,
        'status' => 2,
        'companyCode' => 'ths'
    );
    $res = curl($url, $postData);
    if (200 != $res['httpCode']) {
        $msg = "url:{$url} httpcode:{$res['httpCode']} errorCode:{$res['errorCode']} errorMsg:{$res['errorMsg']}";
        writeLog($msg, 0, $logPath);
        return false;
    }
}
?>
	
	
	
	
	
	
